package com.totoro.rpc.register;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * Created by Niki on 2018/5/7 17:49
 */
public class ZookeeperDiscover implements Discover {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperDiscover.class);
    // TODO: 2018/5/8 zkClient池来获取zkClient实例
    private final ZkClient zkClient;

    public ZookeeperDiscover(String zkAddress, int session_timeout, int connection_timeout) {
        this.zkClient = new ZkClient(zkAddress, session_timeout, connection_timeout);
        LOGGER.debug("discover connect zookeeper");
    }

    public String discover(String serviceName, String version) {
        String servicePath = ZookeeperUtil.serverPath(serviceName, version);
        if (!zkClient.exists(servicePath)) {
            LOGGER.error("服务：{}未注册", serviceName);
            throw new RuntimeException("无服务：" + servicePath);
        }
        Set<String> addresses = zkClient.readData(servicePath);
        if (addresses == null || addresses.isEmpty()) {
            LOGGER.error("服务：{}无可用实例！", serviceName);
            throw new RuntimeException("服务：" + servicePath + "无可用实例！");
        }
        // TODO: 2018/5/8 添加负载功能
        return addresses.iterator().next();
    }
}
